package cn.nawang.ebeim.persist.handler;

import cn.nawang.ebeim.persist.annotation.Column;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: 甘竞存
 * Date: 14-11-10
 * Time: 上午11:16
 * 处理结果集 返回list集合
 */
public class BeanListHandler implements ResultSetHandler {

    private final Class clazz ;

    public BeanListHandler(Class clazz) {
        this.clazz = clazz;
    }

    public Object handler(ResultSet rs) {
        try {
            List list = new ArrayList();
            while (rs.next()) {
                Object bean = clazz.newInstance();
                //得到bean的所有字段
                Field[] declaredFields = clazz.getDeclaredFields();
                for (int i = 0; i < declaredFields.length; i++) {
                    Field field = declaredFields[i];
                    Column annotation = field.getAnnotation(Column.class);
                    String columnName = annotation.value();
                    Object value = rs.getObject(columnName);
                    field.setAccessible(true);
                    field.set(bean,value);
                }
                list.add(bean);
            }
            return list;
        } catch (Exception e) {
            // 再次抛出异常，让上一级去处理
            throw new RuntimeException(e);
        }
    }
}
